package it.eng.area118.mdocommon.android.util;

import it.eng.area118.mdocommon.android.log.BasicLogger;
import it.eng.area118.mdocommon.android.model.AndroidModelContainer;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.res.AssetManager;

/**
 * This class is utility for reading json files embedded into assets directory.
 * 
 * @author Mastroianni
 * 
 */
public class JSONStringReader {

	/**
	 * Reads the content of FILENAME json file embedded into assets directory
	 * 
	 * @param filename
	 *            Name of file Es.comuni.json
	 * @return
	 * @throws Exception
	 */
	public static String readStringFromAssetFile(String filename)
			throws Exception {
		AssetManager assManager = AndroidApplicationContext.getInstance()
				.getApplicationContext().getAssets();
		InputStream is;
		is = assManager.open(filename);
		String retString = readTextFile(is);
		return retString;
	}

	public static String readStringFromCachedAssetFile(String filename,
			String dataCacheName) throws Exception {

		if (AndroidModelContainer.getInstance().getModel(dataCacheName) != null) {
			String data = (String) AndroidModelContainer.getInstance()
					.getModel(dataCacheName);
			BasicLogger.writeLog("ASSET_MANAGER",
					"TRYING TO GETTING DATA FROM CACHE FOR FILE " + filename);
			if (data.length() == 0) {
				BasicLogger.writeLog("ASSET_MANAGER", "READING DATA FROM FILE "
						+ filename);
				AssetManager assManager = AndroidApplicationContext
						.getInstance().getApplicationContext().getAssets();
				InputStream is;
				is = assManager.open(filename);
				String retString = readTextFile(is);
				data = retString;
				AndroidModelContainer.getInstance().putModel(dataCacheName,
						data);
			}

			return data;
		} else {
			AssetManager assManager = AndroidApplicationContext.getInstance()
					.getApplicationContext().getAssets();
			InputStream is;
			is = assManager.open(filename);
			String retString = readTextFile(is);
			AndroidModelContainer.getInstance().putModel(dataCacheName,
					retString);
			return retString;
		}

	}

	public static String readStringFromFile(String filePath) throws Exception {
		FileInputStream is;
		is = new FileInputStream(filePath);
		String retString = readTextFile(is);
		return retString;
	}

	private static String readTextFile(InputStream inputStream) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte buf[] = new byte[1024];
		int len;
		try {
			while ((len = inputStream.read(buf)) != -1) {
				outputStream.write(buf, 0, len);
			}
			outputStream.close();
			inputStream.close();
		} catch (IOException e) {
		}
		return outputStream.toString();
	}
}
